/*
 * @lc app=leetcode.cn id=117 lang=javascript
 *
 * [117] 填充每个节点的下一个右侧节点指针 II
 */

// @lc code=start
/**
 * // Definition for a _Node.
 * function _Node(val, left, right, next) {
 *    this.val = val === undefined ? null : val;
 *    this.left = left === undefined ? null : left;
 *    this.right = right === undefined ? null : right;
 *    this.next = next === undefined ? null : next;
 * };
 */

/**
 * @param {_Node} root
 * @return {_Node}
 */
var connect = function (root) {
  if (!root) return null;
  let queue = [root];
  while (queue.length > 0) {
    const temp = queue;
    queue = [];
    for (let i = 0; i < temp.length; i++) {
      const current = temp[i];
      if (i > 0) {
        temp[i - 1].next = current;
      }
      if (current.left) queue.push(current.left);
      if (current.right) queue.push(current.right);
    }
  }
  return root;
};
// @lc code=end
